package com.jt3g.framework.interceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jt3g.common.annotation.Log;
import com.jt3g.common.enums.BusinessType;
import com.jt3g.common.utils.IpUtils;
import com.jt3g.system.domain.SysBlackListIp;
import com.jt3g.system.service.impl.SysBlackListIpServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.jt3g.common.annotation.RepeatSubmit;
import com.jt3g.common.core.domain.AjaxResult;
import com.jt3g.common.json.JSON;
import com.jt3g.common.utils.ServletUtils;

/**
 * 防止重复提交拦截器
 * 
 * @author ruoyi
 */

@Component
public abstract class RepeatSubmitInterceptor extends HandlerInterceptorAdapter
{


    @Autowired
    private SysBlackListIpServiceImpl  sysBlackListIpServiceImpl;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
            if (annotation != null) {
                if (this.isRepeatSubmit(request)) {
                    AjaxResult ajaxResult = AjaxResult.error("不允许重复提交，请稍后再试");
                    ServletUtils.renderString(response, JSON.marshal(ajaxResult));
                    return false;
                }
            }
            return true;
        } else {
            return super.preHandle(request, response, handler);
        }


    }

    @Log(title = "IP访问记录", businessType = BusinessType.FORCE)
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        String ip = IpUtils.getIpAddr(request);
        System.out.println("当前远程访问IP地址："+ip);
        SysBlackListIp sysBlackListIp  = sysBlackListIpServiceImpl.findByIp(ip);

        if (sysBlackListIp!=null){
            if(sysBlackListIp.getIpbannedtime().before(new Date()) ) returnJson(response,"您的IP地址已经被限制访问！");
        } else {
            //强制控制跳转
            super.postHandle(request, response, handler, modelAndView);

        }
        //super.postHandle(request, response, handler, modelAndView);
    }
    /**
     * 验证是否重复提交由子类实现具体的防重复提交的规则
     * 
    // * @param httpServletRequest
     * @return
     * @throws Exception
     */
    public abstract boolean isRepeatSubmit(HttpServletRequest request) throws Exception;

    private void returnJson(HttpServletResponse response, String json) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);

        } catch (IOException e) {
            //logger.error("response error", e);
        } finally {
            if (writer != null)
                writer.close();
        }
    }

    public void urlHandle(HttpServletRequest request, long limitTime,int limitCount) throws Exception {
        /**
         * 省略业务逻辑部分，参考"准备"步骤
         */
       /* if (count > limitCount){ //符合锁定条件
            Calendar calendar = Calendar.getInstance();
            Date iptime=calendar.getTime();
            BlackList blackList = new BlackList(ip, iptime);
            blackListDao.addBlackList(blackList);
            throw new RequestLimitException();
        }*/
    }
}
